/**
 * @Description: 系统日志
 * @author ourslookAdmin
 * @date 2019-03-08 11:15:35
 */
import React, { Fragment } from 'react';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Form,
  Input,
  message,
  Radio,
  Row,
  Select,
  Spin,
  Tooltip,
  Typography,
  BackTop,
  Tag,
  Icon,
  Divider,
} from 'antd';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import Modal from 'drag-modal';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import ReactJson from 'react-json-view';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '@/components/ourslook/BaseForm';
import ETable from '@/components/ourslook/ETable';
import { getWebPath } from '../../utils/request';
import uiUtils, { hasPermission, rulesReg } from '../../utils/uiUtils';
import styles from '../../utils/ourslook.less';
import Ellipsis from '../../components/ourslook/Ellipsis';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const { Paragraph } = Typography;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const getSourceTypeMap = {
  '0': '系统日志',
  '1': '接口日志',
  '2': '手工日志',
  '3': '异常日志',
  '4': 'app错误',
};

@connect(() => ({}))
class SysLog extends React.Component {
  params = {
    page: 1,
    limit: 100,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 60,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '用户',
      dataIndex: 'username',
      width: 150,
      align: 'left',
      sorter: false,
      render: (value, row, index) => {
        if (value !== row.loginName) {
          if (value !== undefined && row.loginName !== undefined) {
            return `${value}（${row.loginName}）`;
          }
          if (value !== undefined && row.loginName === undefined) {
            return value;
          }
          if (value === undefined && row.loginName !== undefined) {
            return row.loginName;
          }
        } else {
          return value;
        }
        return '--';
      },
    },
    {
      title: '用户IP',
      dataIndex: 'ip',
      width: 120,
      align: 'left',
      sorter: false,
      render: (value, record, index) => {
        let str = value;
        if (str === '0:0:0:0:0:0:0:1' || str === '127.0.0.1') {
          str = '本地';
        }
        return str;
      },
    },
    /*{
      title: '设备信息',
      dataIndex: 'deviceRemark',
      width: 75,
      align: 'left',
      sorter: false,
      render: (value, row, index) => {
        const device = value.toLowerCase().includes('mobile')
          ? 'mobile'
          : value.toLowerCase().includes('computer')
          ? 'computer'
          : 'other';
        let icon = 'frown';
        if (device === 'mobile') {
          icon = 'mobile';
        } else if (device === 'computer') {
          icon = 'desktop';
        }
        return (
          <CopyToClipboard
            text={value}
            onCopy={() => {
              if (device === 'other') {
                this.setState({
                  errorInfo: JSON.parse(value),
                  errorInfoModelVisible: true,
                });
              } else {
                uiUtils.showMessage(
                  formatMessage({ id: 'ours.curd.list.msg.copySuccess' }),
                  'success'
                );
              }
            }}
          >
            <Tooltip
              placement="rightTop"
              title={`${device === 'other' ? '' : value}  ${row.deviceInfo ? row.deviceInfo : ''}`}
            >
              <Button icon={icon}>{device}</Button>
            </Tooltip>
          </CopyToClipboard>
        );
      },
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      width: 75,
      align: 'left',
      sorter: false,
      render(value, row, index) {
        const error = `${value}`.toLowerCase().includes('运行时异常');
        let icon = 'check';
        if (error) {
          icon = 'question';
        }
        return (
          <CopyToClipboard
            text={value}
            onCopy={() => message.success(formatMessage({ id: 'ours.curd.list.msg.copySuccess' }))}
          >
            <Tooltip placement="rightTop" title={value}>
              <Button icon={icon}>method</Button>
            </Tooltip>
          </CopyToClipboard>
        );
      },
    },
    {
      title: '请求参数',
      dataIndex: 'params',
      width: 75,
      align: 'left',
      sorter: false,
      render(value, row, index) {
        return (
          <CopyToClipboard
            text={value}
            onCopy={() => message.success(formatMessage({ id: 'ours.curd.list.msg.copySuccess' }))}
          >
            <Tooltip placement="rightTop" title={value}>
              <Button>params</Button>
            </Tooltip>
          </CopyToClipboard>
        );
      },
    },*/
    { title: '创建时间', dataIndex: 'createDate', width: 180, align: 'center', sorter: true },
    {
      title: '用户操作',
      dataIndex: 'operation',
      width: 180,
      align: 'left',
      sorter: false,
      render: (value, record, index) => {
        if (record.sourceType === 3) {
          return (
            <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
              <Tooltip title={value}>
                <Ellipsis length={25} style={{ color: 'white' }}>
                  {value}
                </Ellipsis>
              </Tooltip>
            </Tag>
          );
        }
        return value;
      },
    },
    {
      title: '操作详情',
      dataIndex: 'operationDetail',
      align: 'left',
      sorter: false,
      render: (value, record, index) =>
        record.operationWarningLevel === 1 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
            <Tooltip title={value}>
              <Ellipsis length={25} style={{ color: 'white' }}>
                {value}
              </Ellipsis>
            </Tooltip>
          </Tag>
        ) : (
          <Tooltip title={value}>
            <Ellipsis length={25}>{value}</Ellipsis>
          </Tooltip>
        ),
    },
    {
      title: '来源类型',
      dataIndex: 'sourceType',
      width: 120,
      fixed: 'right',
      render(value) {
        let desc = getSourceTypeMap[value];
        if (desc === undefined) {
          desc = '';
        }
        return desc;
      },
    },
    {
      title: '操作',
      dataIndex: '',
      width: 80,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('sys:user:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: SysLog.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      errorInfoModelVisible: false, //错误信息json是否显示
      errorInfo: {}, //错误信息json
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'key',
      label: '用户名、用户操作、ip、设备信息、请求参数',
      placeholder: '用户名、用户操作、ip、设备信息、请求参数',
    },
    {
      type: 'SELECT',
      field: 'operation',
      placeholder: '请选择用户操作类型',
      initialValue: '',
      list: [{ id: '', name: '请选择用户操作类型' }],
      showSearch: true,
    },
    {
      type: 'SELECT',
      field: 'sourceType',
      placeholder: '来源类型',
      initialValue: '',
      list: [{ id: '', name: '请选来源类型' }, ...uiUtils.getOptionJsonObjToArr(getSourceTypeMap)],
    },
    {
      type: 'INPUT',
      field: 'deviceInfo',
      label: '设备型号或者设备信息',
      placeholder: '设备型号或者设备信息',
    },
    {
      type: 'DATE_RANGE',
      field: 'createDate',
      label: '操作时间',
      placeholder: ['操作时间', ''],
    },
  ];

  componentDidMount() {
    this.requestList();
    this.getLogOperationList();
  }

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      //const data = `modelIds=${ids.join(',')}&status=3`;
      const data = {
        modelIds: ids.join(','),
        status: 3,
      };
      requestPromise(`${getWebPath('/sys/log/operateSysLogByIds')}`, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: data,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  getInfo = id => {};
  //========其他所有的处理方法，请在按照约定进行处理==========

  getLogOperationList = () => {
    //获取所有的顶级菜单
    requestPromise(`${getWebPath('/sys/log/operationList')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const operationList = res.data || [];
        const newList = [
          { id: '', name: '请选择用户操作类型' },
          ...operationList.map(en => ({ id: en, name: en })),
        ];

        const { formList: formListNew } = this.state;
        const formItem = this.findFormListItemByField('operation');
        formItem.list = newList;
        this.setState({
          formList: formListNew,
        });
      }
    });
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}sys/log/list`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        //marginLeft: 10,
        //marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('sys:log:list')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1200 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>

        {/*查看错误日志json的对话框*/}
        <Modal
          width={800}
          height={600}
          visible={this.state.errorInfoModelVisible}
          title="错误日志"
          onCancel={() => {
            this.setState({
              errorInfoModelVisible: false,
            });
          }}
          saveDistance={0}
          footer={null}
        >
          <ReactJson
            src={this.state.errorInfo}
            theme="apathy"
            iconStyle="circle"
            collapsed
            displayDataTypes={false}
          />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default SysLog;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    if (nextProps.model) {
      this.state = {};
      //使用setFieldsValue实现修改form value的值，不用使用 this.setState({});
      this.props.model.xxx = 'value';
      this.props.form.setFieldsValue({ xxx: 'value' });
    }
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  getUserName = (value, row) => {
    if (value !== undefined && row.loginName !== undefined) {
      return `${value}/${row.loginName}`;
    }
    if (value !== undefined && row.loginName === undefined) {
      return value;
    }
    if (value === undefined && row.loginName !== undefined) {
      return row.loginName;
    }
    return '--';
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="登录名" {...formItemLayout}>
              {this.getUserName(model.username, model)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="用户操作" {...formItemLayout}>
              {model.operation}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="请求url" {...formItemLayout}>
              {model.url}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="请求方法" {...formItemLayout}>
              {model.method}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="请求参数" {...formItemLayout}>
              <Paragraph copyable={{ text: model.params }}>
                <Ellipsis length={50} tooltip>
                  {model.params}
                </Ellipsis>
              </Paragraph>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="ip" {...formItemLayout}>
              {model.ip}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="创建时间" {...formItemLayout}>
              {model.createDate}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="备注信息" {...formItemLayout}>
              <Paragraph copyable={{ text: model.deviceRemark }}>
                <Ellipsis length={50} tooltip>
                  {model.deviceRemark}
                </Ellipsis>
              </Paragraph>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="设备信息" {...formItemLayout}>
              {model.deviceInfo}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="来源类型" {...formItemLayout}>
              {getSourceTypeMap[model.sourceType]}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="操作详情" {...formItemLayout}>
              {model.operationDetail}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
